package com.aoip.telemetry.telemetry.receive.protocol;

import io.netty.buffer.ByteBuf;
import io.netty.handler.codec.DecoderException;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;

import java.nio.ByteOrder;


/**
 * 基于"长度"域编解码器
 *
 * @author chenbai
 * @version 1.0
 * @date 2022/3/1 11:04
 */
public class LengthFieldDecoder extends LengthFieldBasedFrameDecoder {
    private long contentAfterLength;

    public LengthFieldDecoder(int maxFrameLength, int lengthFieldOffset, int lengthFieldLength, int lengthAdjustment, int initialBytesToStrip, int contentAfterLength) {
        super(maxFrameLength, lengthFieldOffset, lengthFieldLength, lengthAdjustment, initialBytesToStrip);
        this.contentAfterLength = contentAfterLength > 0 ? contentAfterLength : 0;
    }

    @Override
    protected long getUnadjustedFrameLength(ByteBuf buf, int offset, int length, ByteOrder order) {
        buf = buf.order(order);
        long frameLength;
        switch (length) {
            case 1:
                frameLength = (long) buf.getUnsignedByte(offset);
                break;
            case 2:
                frameLength = (long) buf.getUnsignedShort(offset);
                break;
            case 3:
                frameLength = (long) buf.getUnsignedMedium(offset);
                break;
            case 4:
                frameLength = buf.getUnsignedInt(offset);
                break;
            case 5:
            case 6:
            case 7:
            default:
                throw new DecoderException("unsupported lengthFieldLength:  (expected: 1, 2, 3, 4, or 8)");
            case 8:
                frameLength = buf.getLong(offset);
                break;
        }
        return frameLength + contentAfterLength;
    }

}
